<template>
  <div :class="forget ? 'forgotPwd' : ''" class="login">
    <el-form
      v-if="!forget"
      ref="loginRef"
      :class="forget ? 'login-form' : 'login-form m-auto'"
      :model="loginForm"
      :rules="loginRules"
    >
      <h3 class="title">福建航信ERP管理系统</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          auto-complete="off"
          placeholder="账号"
          size="large"
          type="text"
        >
          <template #prefix
            ><svg-icon class="el-input__icon input-icon" icon-class="user"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          auto-complete="off"
          show-password
          placeholder="密码"
          size="large"
          type="password"
          @keyup.enter="handleLogin"
        >
          <template #prefix
            ><svg-icon class="el-input__icon input-icon" icon-class="password"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="captchaEnabled" prop="code">
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
          "
        >
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            size="large"
            style="width: 63%"
            @keyup.enter="handleLogin"
          >
            <template #prefix
              ><svg-icon
                class="el-input__icon input-icon"
                icon-class="validCode"
            /></template>
          </el-input>
          <div class="login-code">
            <img
              :src="codeUrl"
              class="login-code-img border-solid border-1 border-slate-200 rounded-lg"
              @click="getCode"
            />
          </div>
        </div>
      </el-form-item>
      <div class="flex justify-between items-center">
        <el-checkbox
          v-model="loginForm.rememberMe"
          style="margin: 0px 0px 25px 0px"
          >记住密码</el-checkbox
        >
        <div
          class="text-14px mb-25px cursor-pointer"
          style="z-index: 1"
          @click="forgetCode"
        >
          忘记密码?
        </div>
      </div>
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          class="login-btn"
          size="large"
          style="width: 100%; height: 45px"
          type="primary"
          @click.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div v-if="register" style="float: right">
          <router-link :to="'/register'" class="link-type"
            >立即注册</router-link
          >
        </div>
      </el-form-item>
    </el-form>
    <ForgotPwd v-if="forget" v-model:forget="forget" />
  </div>
  <el-dialog
    v-model="dialogTableVisible"
    :close-on-click-modal="false"
    title="请选择账号"
    width="35%"
    @close="dialogClose"
  >
    <el-descriptions border column="1" title="">
      <el-descriptions-item
        v-for="(item, index) in identityData"
        :key="index"
        :label="`${item.orgName}-${item.deptName}`"
        align="center"
        label-align="center"
      >
        <el-button link type="primary" @click="changeIdentity(item)">
          {{ item.nickName }}</el-button
        >
      </el-descriptions-item>
    </el-descriptions>
    <!--    <el-table :data="identityData">-->
    <!--      <el-table-column type="index" label="序号" width="50" />-->
    <!--      <el-table-column label="部门名称" prop="deptName"></el-table-column>-->
    <!--      <el-table-column label="用户实名" prop="nickName"></el-table-column>-->
    <!--      <el-table-column label="操作" width="80">-->
    <!--        <template #default="scope">-->
    <!--          <el-button-->
    <!--            type="primary"-->
    <!--            size="small"-->
    <!--            link-->
    <!--            @click="loginIndex(scope.row)"-->
    <!--            >进入</el-button-->
    <!--          >-->
    <!--        </template>-->
    <!--      </el-table-column>-->
    <!--    </el-table>-->
  </el-dialog>
  <change-form
    v-if="dialogVisible"
    :oldPassword="oldPassword"
    @closeDialog="closeDialog"
  ></change-form>
</template>

<script name="Login" setup>
import changeForm from './change.vue'
import { getCodeImg, getInfo } from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'
import useUserStore from '@/store/modules/user'
import { getCurrentInstance, ref } from 'vue'
import { useRouter } from 'vue-router'
import { getUserIdentityList } from '@/api/system/user'
import ForgotPwd from './forgotPwd.vue'
const userStore = useUserStore()
const router = useRouter()
const { proxy } = getCurrentInstance()
const oldPassword = ref('')
const dialogVisible = ref(false)
const loginForm = ref({
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: ''
})
const loginRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
}

const data = reactive({
  identityData: []
})

const { identityData } = toRefs(data)

const codeUrl = ref('')
const loading = ref(false)
// 验证码开关
const captchaEnabled = ref(true)
// 注册开关
const register = ref(false)
const redirect = ref(undefined)
// 弹窗开关
const dialogTableVisible = ref(false)

/**
 * 获取身份列表
 * @param userName 用户username
 */
function getIdentityList(userName) {
  getUserIdentityList(userName).then(res => {
    if (res.data.length > 1) {
      identityData.value = res.data
      dialogTableVisible.value = true
    } else {
      router.push({ path: redirect.value || '/' })
    }
  })
}

/**
 * 切换身份
 */
function changeIdentity(item) {
  // 触发身份切换退出方法
  userStore.changeLogOut().then(() => {
    console.info('item', item)
    let form = {
      username: item.userName
    }
    // 触发身份切换登录方法
    userStore.identityLogin(form).then(() => {
      router.push({ path: redirect.value || '/' })
    })
  })
}

/**
 * 弹窗关闭方法
 */
function dialogClose() {
  router.push({ path: redirect.value || '/' })
}

function handleLogin() {
  sessionStorage.removeItem('questionTypeOptions')
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      // loading.value = true
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set('username', loginForm.value.username, { expires: 30 })
        Cookies.set('password', encrypt(loginForm.value.password), {
          expires: 30
        })
        Cookies.set('rememberMe', loginForm.value.rememberMe, { expires: 30 })
      } else {
        // 否则移除
        Cookies.remove('username')
        Cookies.remove('password')
        Cookies.remove('rememberMe')
      }

      loading.value = true
      // 调用action的登录方法
      userStore
        .login(loginForm.value)
        .then(() => {
          console.log('initpassword===', userStore.initpassword)
          if (userStore.initpassword) {
            loading.value = false
            dialogVisible.value = true
            oldPassword.value = loginForm.value.password
          } else {
            loading.value = false
            getInfo().then(res => {
              sessionStorage.setItem('identityUserName', res.user.userName)
              getIdentityList(res.user.userName)
            })
            // router.push({ path: redirect.value || '/' })
          }
        })
        .catch(() => {
          loading.value = false
          // 重新获取验证码
          if (captchaEnabled.value) {
            getCode()
          }
        })
    }
  })
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value =
      res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      // codeUrl.value = 'data:image/gif;base64,' + res.img
      codeUrl.value = generateVerificationCodeBase64(res.verify)
      loginForm.value.uuid = res.uuid
    }
  })
}

// 前端生成验证码base64图片的函数
function generateVerificationCodeBase64(verificationCode) {
  // 创建一个canvas元素
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')

  // 设置canvas的尺寸
  canvas.width = 100
  canvas.height = 40

  // 在canvas上绘制验证码文本
  ctx.font = '30px Arial'
  ctx.fillStyle = '#0075d9'
  ctx.textBaseline = 'middle'
  ctx.fillText(verificationCode, 10, 20)

  // 添加干扰线
  addInterferenceLines(ctx)

  // 添加验证码背景色
  // ctx.fillStyle = '#eee'
  // ctx.fillRect(0, 0, 100, 40)

  // 将canvas转换为base64图片
  const dataURL = canvas.toDataURL()

  // 将base64图片数据返回
  return dataURL
}

// 添加干扰线的函数
function addInterferenceLines(ctx) {
  for (let i = 0; i < 5; i++) {
    const x1 = Math.random() * 100
    const y1 = Math.random() * 40
    const x2 = Math.random() * 100
    const y2 = Math.random() * 40
    ctx.beginPath()
    ctx.moveTo(x1, y1)
    ctx.lineTo(x2, y2)
    ctx.strokeStyle = '#0075d9'
    ctx.lineWidth = 1
    ctx.stroke()
  }
}

function getCookie() {
  const username = Cookies.get('username')
  const password = Cookies.get('password')
  const rememberMe = Cookies.get('rememberMe')
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password:
      password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  }
}

getCode()
getCookie()
//关闭弹窗
function closeDialog() {
  dialogVisible.value = false
}
const forget = ref(false)
function forgetCode() {
  console.log(1111)
  forget.value = true
}
</script>

<style lang="scss" rel="stylesheet/scss">
.login {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  background-image: url('../../assets/images/login-background.jpg');
  background-size: cover;
  .title {
    font-weight: bold;
    font-size: 24px;
    letter-spacing: 3px;
    -webkit-background-clip: text; //将文字以外的背景切掉
    background-image: linear-gradient(180deg, #19b6ff 0, #0075d9 100%);
    text-shadow: 3px 3px 3px rgba(0, 0, 0, 0.2);
    color: transparent;
    margin: 0px auto 35px auto;
    text-align: center;
    //color: rgb(24, 144, 255);
  }
}
.forgotPwd {
  justify-content: center !important;
  background-image: url('../../assets/images/login-background.jpg') !important;
}
.login-btn {
  box-shadow: 0 8px 25px -8px rgba(70, 166, 255, 0.8);
}
.login-form {
  min-width: 400px;
  border-radius: 10px;
  background: #ffffff;
  padding: 45px 40px 15px 40px;
  .el-input__wrapper {
    border-radius: 8px;
    height: 45px;
    input {
      height: 45px;
    }
  }
  .input-icon {
    height: 45px;
    width: 14px;
    margin-left: 6px;
  }
}
.forgot-form {
  margin-right: 0 !important;
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 45px;
  float: right;
  img {
    width: 100%;
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 45px;
}
</style>
